package com.tanhua.dubbo.api;

import com.tanhua.dubbo.service.TimeLineService;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.mongo.Friend;
import com.tanhua.mongo.Movement;
import com.tanhua.mongo.MovementTimeLine;
import com.tanhua.vo.MovementsVo;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    @Override
    public void saveMovement(Movement movement) {
        movement.setPid(idWorker.getNextId("movement"));
        movement.setCreated(System.currentTimeMillis());
        mongoTemplate.save(movement);
/*

        //保存时间线表,没一个好友保存一条数据
        Query query = Query.query(Criteria.where("userId").is(movement.getUserId()));
        List<Friend> friends = mongoTemplate.find(query,Friend.class);
        for (Friend friend : friends) {
            MovementTimeLine mt = new MovementTimeLine();
            mt.setMovementId(movement.getId());
            mt.setUserId(movement.getUserId());
            mt.setFriendId(friend.getFriendId());
            mt.setCreated(System.currentTimeMillis());
            mongoTemplate.save(mt);
            }
*/
    //2. 保存好友时间线数据
        timeLineService.saveTimeLine(movement.getUserId(), movement.getId());

    }

    @Override
    public PageResult findMyMovements(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = new Query(criteria);
        //查出movement动态表中
        long count = mongoTemplate.count(query, Movement.class);
        //构造分页及按创建时间查询我的动态的分页列表数据
        query.skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize, (int) count,movements);

    }
}
